package com.yswy.common.utils.videoTpGif;

import com.yswy.common.utils.CommandUtil;
import com.yswy.common.utils.HuaWeiYunOBSUtil;
import com.yswy.common.utils.StringUtils;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.EncodingAttributes;
import ws.schild.jave.encode.VideoAttributes;
import ws.schild.jave.info.MultimediaInfo;
import ws.schild.jave.info.VideoInfo;
import ws.schild.jave.info.VideoSize;

import java.io.*;
import java.util.Arrays;
import java.util.UUID;
@Service
@Slf4j
public class VideoToGIf {
    @Value(value = "${VideoToGIf.path}")
    private String sourcePath ;
    //输出格式
    @Value(value = "${VideoToGIf.outputFormat}")
    private String outputFormat = "webp";
    @Value(value = "${VideoToGIf.wh}")
    private Integer wh ;
    @Value(value = "${VideoToGIf.FrameRate}")
    private Integer FrameRate ;

    @Autowired
    private HuaWeiYunOBSUtil huaWeiYunOBSUtil;
    /**
     * 获得转化后的文件名
     *
     * @param sourceFilePath : 源视频文件路径
     * @return
     */
    public String getNewFileName(String sourceFilePath) {
        File source = new File(sourceFilePath);
        String fileName = source.getName().substring(0, source.getName().lastIndexOf("."));
        return fileName + "." + outputFormat;
    }


    /**
     * 转化音频格式
     *
     * @param sourceFilePath : 源视频文件路径
     * @param targetFilePath : 目标gif文件路径
     * @return
     */

    public void transform(String sourceFilePath, String targetFilePath) {
        File source = new File(sourceFilePath);
        File target = new File(targetFilePath);
        try {
            //获得原视频的分辨率
            MultimediaObject mediaObject = new MultimediaObject(source);
            MultimediaInfo multimediaInfo = mediaObject.getInfo();
            VideoInfo videoInfo = multimediaInfo.getVideo();
            VideoSize sourceSize = videoInfo.getSize();
            //设置视频属性
            VideoAttributes video = new VideoAttributes();
            video.setCodec(outputFormat);
            //设置视频帧率 正常为10 ，值越大越流畅
            video.setFrameRate(FrameRate);
            //设置视频分辨率
            VideoSize targetSize = new VideoSize(sourceSize.getWidth()/wh, sourceSize.getHeight()/wh);
            video.setSize(targetSize);
            //设置转码属性
            EncodingAttributes attrs = new EncodingAttributes();
            attrs.setVideoAttributes(video);
            // 音频转换格式类
            Encoder encoder = new Encoder();
            encoder.encode(mediaObject, target, attrs);
            System.out.println("转换已完成...");
        } catch (EncoderException e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量转化视频格式
     *
     * @param sourceFolderPath : 源视频文件夹路径
     * @param targetFolderPath : 目标gif文件夹路径
     * @return
     */
    public void batchTransform(String sourceFolderPath, String targetFolderPath) {
        File sourceFolder = new File(sourceFolderPath);
        if (sourceFolder.list().length != 0) {
            Arrays.asList(sourceFolder.list()).forEach(e -> {
                String outVideoPath =targetFolderPath+ "\\video\\" + e ;
                FfmpegUtil.cutVideoAudio(sourceFolderPath+ "\\" + e,
                        outVideoPath
                        , "00:00:00","00:00:06");

                transform(outVideoPath, targetFolderPath + "\\" + getNewFileName(e));
            });
        }
    }


    /**
     * 批量转化视频格式
     * @return
     */
    public String batchTransform(MultipartFile file) throws IOException {
        //String sourceFolderPath = "C:\\Users\\mxy\\Desktop\\apks\\test\\vdil\\";

        String originalFilename = file.getOriginalFilename();
        originalFilename = UUID.randomUUID()+"." +(StringUtils.isNotEmpty(originalFilename) ? originalFilename.replaceAll("(.*)\\.", "") : "");

        File sourceFolder =new File(sourcePath+originalFilename);
        FileUtils.copyInputStreamToFile(file.getInputStream(), sourceFolder);


        String outVideoFilename = UUID.randomUUID()+"." +(StringUtils.isNotEmpty(originalFilename) ? originalFilename.replaceAll("(.*)\\.", "") : "");
        String outVideoPath =sourcePath + outVideoFilename ;
        File outVideo = new File(outVideoPath);


        FfmpegUtil.cutVideoAudio(sourcePath+originalFilename,
                outVideoPath
                , "00:00:00","00:00:04");
        String gifFilePath = sourcePath  + getNewFileName(outVideoPath) ;
        transform(outVideoPath, gifFilePath);
        File gifFile = new File(gifFilePath);
        InputStream inputStream = new FileInputStream(gifFile);
        String gifUrl = huaWeiYunOBSUtil.asyncUpload(String.format("imgeffect/ImgEffect/videoOld/%s.%s", UUID.randomUUID(), outputFormat), inputStream);



        sourceFolder.delete();
        gifFile.delete();
        outVideo.delete();
        return gifUrl;
    }


    public static void main(String[] args) throws IOException {
//        batchTransform("C:\\Users\\mxy\\Desktop\\apks\\test\\vdil", "C:\\Users\\mxy\\Desktop\\apks\\test\\gif");


    }


}